﻿using Enum;
using MediatR;
using Practice.Common.Domains;
using Practice.Common.Dto;
using Practice.Common.Infrastructure.Interfaces;

namespace Practice.API.Application.Commands.Roles
{
    public class RoleListHandler : IRequestHandler<RoleListCommand, Result>
    {
        public readonly IBaseRepository<Role> RoleRepository;
        public readonly IBaseRepository<RolePermission> RolePermissionRepository;

        public RoleListHandler(IBaseRepository<Role> roleRepository, IBaseRepository<RolePermission> rolePermissionRepository)
        {
            RoleRepository = roleRepository;
            RolePermissionRepository = rolePermissionRepository;
        }

        public async Task<Result> Handle(RoleListCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonEnumCode.Success };
            var res = new PageResult() { };
            try
            {
                var list = (from a in RoleRepository.GetAll()
                           join b in RolePermissionRepository.GetAll() on a.RoleId equals b.RoleId
                           select new RoleListDto() {
                            RoleId=a.RoleId,
                            PermissionMassage=b.PermissionMassage,
                            CreateTime=b.CreateTime,
                            RoleName=a.RoleName,
                            RoleStatus=a.RoleStatus,
                           }).ToList();
                
                res.TotalCount=list.Count;
                res.PageCount=(int)Math.Ceiling(list.Count*1.0/request.pagesize);
                res.Data = list.OrderBy(x=>x.CreateTime).Skip((request.pageindex-1)*request.pagesize).Take(request.pagesize).ToList();
                if (request.RoleName != null)
                {
                    list = list.Where(x => x.RoleName.Contains(request.RoleName)).ToList();
                }

                result.Data = res;
                result.Code = (int)CommonEnumCode.Success;



            }
            catch (Exception)
            {

                result.Msg = "显示查询失败";

            }
            return result;
        }
    }
    public class PageResult
    {
        public int PageCount { get; set; }
        public int TotalCount { get; set; }
        public List<RoleListDto> Data { get; set; }
    }
    public class RoleListDto
    {
        public int RoleId { get; set; }
        public string RoleName { get; set; }
        public string PermissionMassage { get; set; }
        public string CreateTime { get; set; } = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
        public bool RoleStatus { get; set; }
    }
}
